<!--
 * @Author: hye0228 1261769443@qq.com
 * @Date: 2022-10-11 15:23:38
 * @LastEditors: hye0228 1261769443@qq.com
 * @LastEditTime: 2022-10-11 17:27:23
 * @FilePath: \v2.0.0\src\views\admin\authority\components\MenuTree.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-drawer
    :model-value="visible"
    :show-close="false"
    :close-on-click-modal="false"
  >
    <template #default>
      <el-tree
        ref="treeRef"
        v-loading="loading"
        :data="menuTreeList"
        :props="defaultProps"
        highlight-current
        show-checkbox
        node-key="id"
        accordion
      />
    </template>
    <template #footer>
      <div class="flex">
        <el-button size="large" class="flex-1" @click="handleClose">
          取消
        </el-button>
        <el-button size="large" class="flex-1" @click="handleClear">
          清空
        </el-button>
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          class="flex-1"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup>
import { ref, toRefs, watch } from "vue";
import { fetchTreeList } from "@/api/menu.js";
import { listMenuByRole, allocMenu } from "@/api/role.js";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: Number,
    default: null,
  },
});

const { id, visible } = toRefs(props);

watch(id, (newValue) => {
  if (!newValue) return;
  getRoleMenu();
});

const menuTreeList = ref([]);

const defaultProps = {
  children: "children",
  label: "title",
};

const emit = defineEmits(["update:visible", "confirm"]);

function handleClose() {
  emit("update:visible", false);
}

const loading = ref(false);
async function getMenuTree() {
  loading.value = true;
  const res = await fetchTreeList();
  loading.value = false;
  menuTreeList.value = res.data;
}

getMenuTree();

const treeRef = ref(null);
async function getRoleMenu() {
  const res = await listMenuByRole(id.value);
  const checkedKeys = res.data.map((item) => item.id);
  treeRef.value.setCheckedKeys(checkedKeys);
}

function handleClear() {
  treeRef.value.setCheckedKeys([]);
}

async function handleSave() {
  const checkedKeys = treeRef.value.getCheckedKeys(true);
  const data = new FormData();
  data.append("roleId", id.value);
  data.append("menuIds", checkedKeys);
  loading.value = true;
  await allocMenu(data);
  loading.value = false;
  emit("update:visible", false);
}
</script>
